package com.huawei.cloud.rc.controller;

import com.huawei.cloud.rc.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

/**
 * Created by cwx183898 on 2017/5/23.
 */
@RestController
public class RcController {
    @Autowired
    LoadBalancerClient client;

    @RequestMapping(path = "/rc/get")
    public User get(String username, String password) {
        ServiceInstance instance = client.choose("user-services");
        if (instance != null) {
            URI uri = instance.getUri();

            LinkedMultiValueMap map = new LinkedMultiValueMap(0);
            map.add("username", username);
            map.add("password", password);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            HttpEntity<LinkedMultiValueMap> entity = new HttpEntity<LinkedMultiValueMap>(map, headers);
            return (new RestTemplate()).postForEntity(uri.toString() + "/user/get", entity, User.class).getBody();
        }
        return null;
    }

}
